// Copyright 2006 Google Inc. All Rights Reserved.

/***************************** MENU *****************************/

var PY_fileMenuExtras = null;

var tagsToApply = null;
var tagsToRemove = null;

var JS_TAG = '<TAG1>';
var HTML_TAG = '<TAG2>';
var applyString =
    "<tr class=menu_row_unsel name=menu_row onclick=\"AddTag('" + JS_TAG + "')\">" +
    "<td><img border=0 class=menu_cb src=\"images/blankdot.gif\"></td>" +
    "<td class=menu_cell><nobr>&nbsp;&nbsp;&nbsp;" + HTML_TAG + "&nbsp;</nobr></td>" +
    "<td class=menu_accel><nobr>&nbsp;</nobr></td></tr>";
var removeString = applyString.replace("AddTag", "RemoveTag");

function ActionMenuLoader(element, which)
{
  var selection = getSelectionCombination();

  if (selection == DocumentSelection.NONE) {
    ShowToolbarMenu(Build_ActionMenu, element);
  } else if (which == 'more') {
    ShowToolbarMenu(Build_MoreMenu, element);
  } else {
    var allTags = listData.getAllTags().sort(caseInsensitiveCompare);
    var removeTags = getExistingTagList().sort(caseInsensitiveCompare);
    
    tagsToApply = generateTagHtml(applyString, allTags);
    tagsToRemove = generateTagHtml(removeString, removeTags);

    if (which == 'tag') {
      ShowToolbarMenu(Build_TagMenu, element);
    }
  }

  return false;
}


function htmlEncodeTag(s) {
  s = s.replace( /&/g, "&amp;");
  s = s.replace( /</g, "&lt;");
  s = s.replace( />/g, "&gt;");
  s = s.replace( /\"/g, "&quot;");

  return s;
}

function jsEncodeTag(s) {
  var result = htmlEncodeTag(s);
  
  result = result.replace( /\'/g, "\\\'");

  return result;
}

/**
 * Generate the HTML for the tag menu given the specified templates and
 * list of tags.
 */
function generateTagHtml(templateSource, tags) {
  var result = "";
  var js_pattern = new RegExp(JS_TAG, "g");
  var html_pattern = new RegExp(HTML_TAG, "g");

  for (var i = 0; i < tags.length; i++) {
    var htmlTag = htmlEncodeTag(tags[i]);
    var jsTag = jsEncodeTag(tags[i]);

    var s = templateSource.replace(js_pattern, jsTag);
    result += s.replace(html_pattern, htmlTag);
  }
  
  return result;
}

/**
 * Walk the checkboxes and return the set of tags currently on the documents.
 */
function getExistingTagList() {
  var tags = new Array();

  walkCheckboxes(
      function f(cb) {
        var id = cb.name.substring("list_cb".length);
        var row = listData.getRow(id);

        if (row == null) {
          return;
        }

        if (cb.checked) {
          var theseTags = row.getTagList();

          for (var i = 0; i < theseTags.length; i++) {
            addUnique(tags, theseTags[i]);
          }
        }
      }
    );

  return tags;
}

/**
 * Compare two values, coersing to strings first.
 */
function caseInsensitiveCompare(x, y) {
  var lowerX = String(x).toLowerCase();
  var lowerY = String(y).toLowerCase();

  if (lowerX > lowerY) {
    return 1;
  } else if (lowerX < lowerY) {
    return -1;
  } else {
    return 0;
  }
}

function SplitAndEval(str1, str2)
{
  var strs = str1.split(str2);
  if (strs != null && strs.length > 0)
  {
    var res = "";
    for (var i = 0; i < strs.length; i++)
    {
      if (strs[i] != null && strs[i].length > 0)
        res += eval(strs[i].replace("\\'", "\\\\'"));
    }

    return res;
  }
  return null;
}

function IsEditorPage()
{
  return actionDocID != null;
}

function ShowDocumentMenu(element, docid, isWritelyDoc, documentActions)
{
  if (!ShouldShowMenu(element, false))
    return false;

  try {
    var text;

    if (isWritelyDoc) {
      text = Build_DocumentMenu(docid);
    } else {
      text = Build_DocumentMenuExternal(docid, documentActions);
    }

    if (text != null)
    {
      document.getElementById("MENU").innerHTML = text;
      document.getElementById("MENU").normalize();
      ShowMenu(element, "MENU", docid, false, null);
    }

    return false;
  } catch (ex) {
    rce("ActionMenu.ShowDocumentMenu", ex, "failed to build menu: " + text + " "
        + element);
  }
}

function Build_DocumentMenu(docid)
{
  try {
	var t = Menu_TableStart("");

    t += Menu_Row(MSG_EDIT, "DocAction('edit', true, '" + docid + "', '')");
	t += Menu_Separator(1);
    t += Menu_Row(MSG_COLLABORATE, "DocAction('share', true, '" + docid + "', '')");
    t += Menu_Row(MSG_PUBLISH, "DocAction('publish', true, '" + docid + "', '')");
    t += Menu_Row(MSG_REVISIONS, "DocAction('revbrowse', true, '" + docid + "', '')");
	t += Menu_Separator(1);
    t += Menu_Row(MSG_PREVIEW, "DocAction('preview', true, '" + docid + "', '')");

    t += Menu_TableEnd();
    return t;
    
  } catch (ex) { 
    rce("Build_DocumentMenu", ex, "Menu so far: " + t);
    return "";
  }
}

// Execute a menu command for an external document
// Probably want to inject the id with some more powerful sprintf style
// mechanism
function DoExternalAction(name, url, id) {
  return popupWindow(url, name, false)
}

// Generate the document menu for an external resources
// action_ids is a string containing a comma-separated list of indexes into
// url_actions and url_names.
function Build_DocumentMenuExternal(docid, action_ids)
{
  try {
    var t = Menu_TableStart("");
    var ids = action_ids.split(",");

    for (i = 0; i < ids.length; i++) {
      var ind = ids[i];
      if (ind == "##SEP") {
        t += Menu_Separator(1);
      } else if (url_actions[ind] != null) {
        t += Menu_Row(url_names[ind],
          "DoExternalAction('" + url_names[ind] + "','" + url_actions[ind] +"','" + docid + "')");
      }
    }

    t += Menu_TableEnd();
    return t;
  } catch (ex) { 
    rce("Build_DocumentMenuExternal", ex, "Menu so far: " + t);
    return "";
  }
}

var url_actions = new Array();
var url_names = new Array();

function initActions() {
  url_actions = new Array();
  url_names = new Array();
}

function newAction(name, url) {
  url_names[url_names.length] = name;
  url_actions[url_actions.length] = url;
}

function Build_TagMenu()
{
  try {
	var t = Menu_TableStart("");

	if (GetActionDocsString(actionDocID) == "")
		t += Menu_Row(MSG_NO_DOCUMENTS_SELECTED, "alert(MSG_ALERT_NDS)");
	else
	  t = AddTagMenu(t);

    t += Menu_TableEnd();
    return t;
    
  } catch (ex) { 
    rce("Build_TagMenu", ex, "Menu so far: " + t);
    return "";
  }
}

function Build_MoreMenu()
{
  try {
	var t = Menu_TableStart("");

    var sayDoc = (IsEditorPage()) ? " document" : "";

	if (GetActionDocsString(actionDocID) == "")
	  t += Menu_Row(MSG_NO_DOCUMENTS_SELECTED, "alert(MSG_ALERT_NDS)");
	else
	  t = AddMoreMenu(t, sayDoc);

    t += Menu_TableEnd();
    return t;
  } catch (ex) { 
    rce("Build_MoreMenu", ex, "Menu so far: " + t);
    return "";
  }
}

function AddTagMenu(t)
{
  try {
    if (tagsToApply != null && tagsToApply.length > 0) {
	  if (tagsToRemove != null && tagsToRemove.length > 0) {
  		t += Menu_Label(MSG_REMOVE_TAG);
	  	t += tagsToRemove;
	  }
	  t += Menu_Label(MSG_APPLY_TAG);
	  t += tagsToApply;
	  t += Menu_Separator(2);
	}
	else if (tagsToRemove != null && tagsToRemove.length > 0)
	  t += Menu_Label(MSG_APPLY_TAG);

    tagsToApply = null;
    tagsToRemove = null;

    t += Menu_Row(MSG_NEW_TAG, "NewTag(true)");
    t += Menu_Row(MSG_MULTIPLE_TAGS, "NewTag(false)");
    return t;
  } catch (ex) { 
    rce("AddTagMenu", ex, "Menu so far: " + t);
    return "";
  }
}

function AddMoreMenu(t, sayDoc)
{
  try {
  //actionDocId is the doc id of the current editor. SelDocs are documents selected in the current window.
  //If we have a single document selected, *or* we're in the editor, we can have the copy command.
  var selDocCount = SelDocCount(actionDocID);
  var toCopy = actionDocID;

  if (toCopy == null && selDocCount == 1) {
    toCopy = GetSelDocArray(actionDocID)[0];
  }

  var selection = getSelectionCombination();
  var isTrixDoc =
      ((selection == DocumentSelection.MIXED) ||
       (selection == DocumentSelection.ONE_TRIX) ||
       (selection == DocumentSelection.N_TRIX));

  if (IsEditorPage()) {
	if (TabIsEditor) {
      t += Menu_Row(MSG_NEW_DOCUMENT, "SaveDocContentsWithNotify(function() {createNewDoc('Untitled', '', false, '');})");
      t += MenuAccel_Row(MSG_SAVE_DOCUMENT, "SaveDocContentsWithNotify(null)", "Ctrl-S");
      t += Menu_Separator(2);
      if (typeof PY_fileMenuExtras != "undefined" && PY_fileMenuExtras) {
        t += PY_fileMenuExtras;
        t += Menu_Separator(2);
      }
    }
  }

  if (!isTrixDoc) {
    t += Menu_Row(MSG_SAVE_AS_HTML, "DownloadDocsAsZip()");
    if (selDocCount == 1) {
      t += Menu_Row(MSG_SAVE_AS_RTF, "DownloadDocsAsX('rtf')");
      t += Menu_Row(MSG_SAVE_AS_WORD, "DownloadDocsAsX('doc')");
      t += Menu_Row(MSG_SAVE_AS_OO, "DownloadDocsAsX('oo')");
      t += Menu_Row(MSG_SAVE_AS_PDF, "DownloadDocsAsX('pdf')");
    }

    t += Menu_Separator(2);
    if (toCopy != null) {
	  if (IsEditorPage() && typeof(SaveDocContentsWithNotify) != "undefined")
	    t += Menu_Row(MSG_COPY, "SaveDocContentsWithNotify(function() { CopyDocument('" + toCopy + "', true) })");
 	  else
	    t += Menu_Row(MSG_COPY, "CopyDocument('" + toCopy + "', false)");
    }
  }

  if (IsEditorPage()) {
	  if (TabIsEditor) {
	    t += Menu_Row(MSG_RENAME, "RenameDocument()");
	    t += Menu_Row(MSG_PRINT_DOCUMENT, "PrintDocument('" + toCopy + "')");
	    t += Menu_Separator(2);
	    t += Menu_Row(MSG_COUNT_WORDS, "CountDocumentWords()");
	    t += MenuAccel_Row(MSG_FIND_AND_REPLACE, "FindAndReplaceDlg()", MSG_EXPERIMENTAL);
	   }
  }
  
  if (!IsEditorPage()) {
    if (actionDocID == null) {
      t += Menu_Row(MSG_STAR, "StarListDocs(true)");
      t += Menu_Row(MSG_UN_STAR, "StarListDocs(false)");
      t += Menu_Separator(2);
    }

    if (!isTrixDoc) {
      t += Menu_Row(MSG_UN_COLLABORATE_ME, "RemoveFromDocs(RemoveResults)");
    }
  }

  //if (IsEditorPage())
  //t += Menu_RowRSS(MSG_DOCUMENT_RSS_FEED, "ShowDocRSSFeed()");
  return t;
  } catch (ex) { 
    rce("AddMoreMenu", ex, "Menu so far: " + t);
    return "";
  }
}

function Build_ActionMenu()
{
  try {
  var t = Menu_TableStart("");
  var isHome = action == "" || action == "rs" || action == "home";

  idDoc = actionDocID;

  var sayDoc = (IsEditorPage()) ? " document" : "";

  if (GetActionDocsString(actionDocID) == "")
	t += Menu_Row(MSG_NO_DOCUMENTS_SELECTED, "alert(MSG_ALERT_NDS)");
  else if (action == "archived_docs")
  {
    t += Menu_Row("Undelete" + sayDoc, "ArchiveDocument(false)");
  }
  else
  {
    if (!IsEditorPage())
    {
      t += Menu_Row("Unarchive", "ActivateDocument(false)");
      if (!isHome)
        t += Menu_Row("Archive", "ActivateDocument(true)");
    }
    t = AddMoreMenu(t, sayDoc);
  }

  t += Menu_TableEnd();

  return t;
  } catch (ex) { 
    rce("Build_ActionMenu", ex, "Menu so far: " + t);
    return "";
  }
}

function ShowToolbarMenu(menuBuilder, element, opt_docid)
{
  if (!ShouldShowMenu(element, false))
		return false;

	try	{
    var text = menuBuilder(opt_docid);
    if (text != null)
    {
		  document.getElementById("ActionMenu").innerHTML = text;
		  document.getElementById("ActionMenu").normalize();
		  ShowMenu(element, "ActionMenu", opt_docid, true, null);
	  }
    return false;
  } catch (ex) { rce("ActionMenu.ShowToolbarMenu", ex, "failed to build menu: " + menuBuilder + " " + element); }
}

function Menu_TableStart(w) 						{ return menuMakeTable(w); }
function Menu_TableEnd(cs)   						{ return '</table>'; }
function Menu_Label(strText) 						{ return menuMakeLabelRow(strText); }
function Menu_Separator(cs)  						{ return menuMakeSep(); }
function Menu_Row(strText, strCmd) 					{ return menuMakeRow(strText, strCmd, "", ""); }
function MenuAccel_Row(strText, strCmd, strAccel) 	{ return menuMakeRow(strText, strCmd, strAccel, ""); }
function Menu_RowRSS(strText, strCmd) 				{ return menuMakeRow(strText, strCmd, "<img align=absmiddle style=\"margin:4px;\" src=/images/xmlhere.gif border=0>", "") }

/**************************************** COMMANDS *******************************/


/**
 * Walk the document checkboxes on the form and execute the function f for each.
 */
function walkCheckboxes(f) {
  var cbs = document.body.getElementsByTagName("input");
  if (cbs != null) {
    for (var i = 0; i < cbs.length; i++) {
      var cb = cbs[i];
      if (cb.name.indexOf("list_cb") == 0) {
        f(cb);
      }
    }
  }
}

/**
 * Return the array of selected document values.
 */
function GetSelDocArray(doc)
{
  var result = new Array();
  if (doc != null && doc != "") {
    result.push(doc);
    return result;
  }

  walkCheckboxes(
      function(cb) {
        if (cb.checked) {
          result.push(cb.value);
        }
      });

  return result;
}

function GetActionDocsString(doc) { return GetSelDocArray(doc).join(","); }
function SelDocCount(doc) { return GetSelDocArray(doc).length; }

function DoUserMiscCommandOnDocs(commandName, extraParams, opt_callback)
{
	try	{
	  var docString = GetActionDocsString(actionDocID);
	  if (docString == null || docString == "")
		  return;

	  SetListCursor("wait");
	  asyncPOST("command=" + commandName + "&docID=" + docString + extraParams, "/UserMiscCommands",
			  	function (req, timedOut)
			  	{
	  				SetListCursor("default");
			  		if (typeof(opt_callback) != "undefined" && opt_callback != null)
			  			opt_callback(req, timedOut);
			  		else
			  			checkAndReloadDocList(req, timedOut);;
			  	},
				"MiscCommands_" + commandName + docString );

	} catch (ex) { rce("DoUserMiscCommandOnDocs", ex, "commandName: " + commandName + " extraParams: " + extraParams); }
}

function CopyDocument(docID, doPrompt)
{
	var extra = "";
	if (doPrompt) {
		if (IsEditorPage()) {
			if (IsShared) {
				if (confirm("Click OK to copy the collaborators,\nor Cancel to just copy the document."))
					extra = "&copycollaborators";
			}
		} else {
			if (confirm("Click OK to copy the collaborators (if any),\nor Cancel to just copy the document."))
				extra = "&copycollaborators";
		}
	}
	var url = "/?action=copy&docid=" + docID + extra;
	return popupWindow(url, "Editor_" + docID, false);
}

function TryToArchive(setArchive)
{
  //alert("TryToArchive");
  if (CountNumberOfDocs() == 0)
    alert(MSG_ALERT_NDS);
   else
    ArchiveDocument(setArchive);
}

function TryToActivate(setActive)
{
  if (CountNumberOfDocs() == 0)
    alert(MSG_ALERT_NDS);
   else
    ActivateDocument(setActive);
}

function RemoveTag(toRemove)
{
  var cb = null;
  if (IsEditorPage())
  {
    ShowWorkingDiv();
    cb = function (req, timedOut)
    {
		if (ReqErrorAlert(req, timedOut)) return false;
	    if (req.responseText.indexOf("not allowed to edit") != -1)
	    	alert(MSG_NO_DOC_PERMISSIONS);
	    SetResult("<nobr>Removed tag.</nobr>", "savedNotice", 8000);
    };
  }
        DoUserMiscCommandOnDocs("changeTags", "&removetags=" + encodeURIComponent(toRemove.replace("&apos;", "'")), cb);
	return false;
}

function AddTag(toAdd)
{
  var cb = null;
  if (IsEditorPage())
  {
    ShowWorkingDiv();
    cb = function (req, timedOut)
    {
		if (ReqErrorAlert(req, timedOut)) return false;
	    if (req.responseText.indexOf("not allowed to edit") != -1)
	    	alert(MSG_NO_DOC_PERMISSIONS);
	    SetResult("<nobr>Added tag.</nobr>", "savedNotice", 8000);
    };
  }
	DoUserMiscCommandOnDocs("changeTags", "&addtags=" + encodeURIComponent(toAdd.replace("&apos;", "'")), cb);
	return false;
}

function RenameDocument()
{
  if (typeof(lastSavedTitle) == "undefined" || lastSavedTitle == null) return;

  HideMenus(true);
  var newName = Prompt(MSG_ENTER_NEW_DOC_NAME, lastSavedTitle);

  if (newName != null && newName.length > 0)
  {
  	if (typeof SaveDocContents != "undefined")
  	{
		 SaveDocContentsWithNotify(
		    function () {
              ShowWorkingDiv();
              asyncPOST("command=rename_doc&docid=" + DocID + "&name=" + encodeURIComponent(newName), 
                        "MiscCommands", 
                        function(req, timedOut) { 
                          ShowNewTitle(newName); 
                        })
            });
    }
  }
  return false;	
}

function ShowNewTitle(newName) {
  HideWorkingDiv();
  lastSavedTitle = newName;
  docTitle = newName;
  var oTitle = document.getElementById('txtTitle');
  if (oTitle != null) 
    oTitle.innerHTML = htmlEncodeTag(newName);
  document.title = lastSavedTitle + " - Docs & Spreadsheets";
  ReloadOpener(false);
}

function NewTag(justnew)
{
  HideMenus(true);
  var toAdd = Prompt((justnew) ? MSG_ENTER_NEW_TAG : MSG_ENTER_CSTS);
  if (toAdd == null)
    return false;

  while (justnew && toAdd.length > 26)
  {
    alert(MSG_PLEASE_SHORTEN_TAG);
    toAdd = Prompt(MSG_ENTER_NEW_TAG, toAdd);
  }
  if (toAdd != null)
    AddTag(toAdd);
	return false;
}

function StarDocument(doc, event)
{
	var evtClass = getEventElement(event).className;

	var isStarred = (evtClass == 'st2');
	setEventElementClass( event, isStarred ? 'st1' : 'st2');

	SetListCursor("wait");
	asyncPOST("command=setstar&docID=" + doc +
			   "&starred=" + ((isStarred) ? "false" : "true"), //flip the state
			"UserMiscCommands",
			 function (req, timedOut) { checkAndReloadDocList(req, timedOut); }, "starDocument_" + doc );

    return false;
}

function checkAndReloadDocList(req, timedOut) {
  if (ifOK(req, timedOut)) { 
    SetListCursor("default"); 
    ReloadDocLists(window); 
    return true;
  }
  return false;
}

function ifOK(req, timedOut) {
  if (req == null || timedOut) {
    alert(MSG_UNABLE_TO_CONNECT_TO_SERVER);
    return false;
  } else if (IsErrorMsg(req.responseText)) {
  	if (GetErrorMsg(req.responseText) == "signedout")
      redirectToLogin();
    else 
      alert(GetErrorMsg(req.responseText));
    return false;
  }
  return true;
}

function RemoveFromDocs(callback)
{
  HideMenus(true);

  if (!confirm((CountNumberOfDocs() <= 1) ? MSG_REALLY_REMOVE_SING :
                                          MSG_REALLY_REMOVE_PLUR))
	  return;

	var docString = GetActionDocsString(actionDocID);
	if (docString == null || docString == "")
		return;

	SetListCursor("wait");
	asyncPOST("command=removeFromDocs&docID=" + docString,
			"UserMiscCommands",
			 function (req, timedOut) { if (checkAndReloadDocList(req, timedOut) && callback) callback(req); }, "removeFromDocs_" + docString );
}

function RemoveResults(req)
{
  if (req.responseText != "success")
    alert(req.responseText);
  else if (IsEditorPage())
    DoneButtonClicked(null);
}

function StarListDocs(setStar)
{
	DoUserMiscCommandOnDocs("setstar", "&starred=" + ((setStar) ? "true" : "false"));
	return false;
}

function ActivateDocument(setActive)
{
	DoUserMiscCommandOnDocs("setactive", "&active=" + ((setActive) ? "true" : "false"));
	return false;
}

function DownloadDocsAsX(expFormat)
{
	var docString = GetActionDocsString(actionDocID);
	if (docString == null || docString == "")
		return false;

	var exportFormatParam = "&exportFormat=" + expFormat;

	if (typeof SaveDocContents != "undefined")
		SaveDocContents(true, function () {
		window.location = "MiscCommands?command=saveasdoc&docID=" + docString + exportFormatParam;
		 }
		 );
	else
		window.location = "MiscCommands?command=saveasdoc&docID=" + docString + exportFormatParam;

	return false;
}

function DownloadDocsAsZip()
{
	var docString = GetActionDocsString(actionDocID);
	if (docString == null || docString == "")
		return false;

	if (typeof SaveDocContents != "undefined")
		SaveDocContents(true, function () {
		window.location = "UserMiscCommands?command=saveaszip&docID=" + docString;
		 }
		 );
	else
		window.location = "UserMiscCommands?command=saveaszip&docID=" + docString;

	return false;
}

function ShowDocRSSFeed()
{
  if (IsPublic || IsRSSOK)
    HeresThatRSSFeed();
  else
    ShowEditorDialog("Dialogs/RSSApproval", SaveAndShowThatFeed);
}

function SaveAndShowThatFeed(saveSetting, setting)
{
  if (saveSetting)
  {
    IsRSSOK = setting;
    asyncPOST("command=allowprivaterss&yes=" + setting.toString(), "UserMiscCommands", HeresThatRSSFeed);
  }
}

function HeresThatRSSFeed()
{
  var docString = GetActionDocsString(actionDocID);  //should be only 1!
  var sampleLink = GetMashedURL("RSSFeed", "userID=" + userID + "&authToken=" + rssAuthToken + "&revisioncount=10&docid=" + docString + "&x=");
 	popupWindow(sampleLink, "RSSFeed", false);
}

function CountDocumentWords()
{
  HideMenus();
	if (typeof SaveDocContents != "undefined")
		SaveDocContents(true, function () { ShowEditorDialog('Dialogs/WordCount');} );
	else
    ShowEditorDialog('Dialogs/WordCount');
}

function ArchiveDocument(setArchive)
{
	if (setArchive)
	{
	  HideMenus(true);
    if (!confirm((CountNumberOfDocs() <= 1) ? MSG_REALLY_DELETE_SING :
                                            MSG_REALLY_DELETE_PLUR))
	    return;
	}

	var callback = (actionDocID != null) ? function() {  DoneButtonClicked(null); } : checkAndReloadDocList;
	DoUserMiscCommandOnDocs("setarchive", "&archived=" + ((setArchive) ? "true" : "false"), callback);
  return false;
}

// Return the number of documents currently selected
function CountNumberOfDocs(opt_doc)
{
  if (opt_doc != null && opt_doc != "") {
    return 1;
  }

  var count = 0;

  walkCheckboxes(
      function(cb) {
        if (cb.checked) {
          count++;
        }
      })

  return count;
}

// Return an indication of what kind of documents are selected..  The results
// are:
//    DocumentSelection.NONE = no documents selected
//    DocumentSelection.ONE_WRITELY = one writely document selected
//    DocumentSelection.N_WRITELY = N writely documents selected
//    DocumentSelection.ONE_TRIX = one trix (external) document selected
//    DocumentSelection.N_TRIX = N trix documents selected
//    DocumentSelection.MIXED = One or more of both types
//

var DocumentSelection = {
  NONE: 0,
  ONE_WRITELY: 1,
  N_WRITELY: 2,
  ONE_TRIX: -1,
  N_TRIX: -2,
  MIXED: 100
};

function getSelectionCombination() {
  var writelyCount = 0;
  var trixCount = 0;

  walkCheckboxes(
      function f(cb) {
        if (cb.checked) {
          var id = cb.name.substring("list_cb".length);
          var row = listData.getRow(id)

          if (row == null) {  // Remove post-leftly
            writelyCount++;
          } else if (row.isWritelyDoc()) {
            writelyCount++;
          } else {
            trixCount++;
          }
        }
      })

  if (trixCount == 0) {
    if (writelyCount == 0) {
      return DocumentSelection.NONE;
    } else if (writelyCount == 1) {
      return DocumentSelection.ONE_WRITELY;
    } else {
      return DocumentSelection.N_WRITELY;
    }
  } else if (writelyCount > 0) {
    return DocumentSelection.MIXED;
  } else if (trixCount == 1) {
    return DocumentSelection.ONE_TRIX;
  } else {
    return DocumentSelection.N_TRIX;
  }
}
